﻿using XW.Utils;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Caching.Distributed;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using XW.Core;

namespace XW.Web.Framework.Jwt
{
    /// <summary>
    /// 
    /// </summary>
    public static class JwtTokenHelper
    {
        //private const string COOKIE_ADMIN_TOKEN = "Admin-Token";
   

        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="_jwtOptions">The JWT options.</param>
        /// <param name="user_id">The user identifier.</param>
        /// <param name="organization">The organization.</param>
        /// <param name="realName">Name of the real.</param>
        /// <param name="is_sup">The is sup.</param>
        /// <returns></returns>
        public static string LoginAndGetToken(HttpContext context,JwtSecurityTokenOptions _jwtOptions,string user_id,string organization,string? realName,string is_sup,string system) {
            var claims = new[]
                    {
                    new Claim(JwtTokenConst.JWT_USER_ID, user_id),
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    // 组织ID
                    new Claim(JwtTokenConst.JWT_ORGANIZATION, organization.ToString()),
                    // 姓名
                    new Claim(JwtTokenConst.JWT_REAL_NAME, realName??""),
                    //new Claim("dep_id", dep_id.ToString()),
                    new Claim(JwtTokenConst.JWT_SUP_ADMIN,is_sup),
                    //new Claim("remoteCode",remoteCode??""),
                    new Claim(JwtTokenConst.JWT_SYSTEM,system)
                }; 
            var claimsIdentity = new ClaimsIdentity(
               claims,
               CookieAuthenticationDefaults.AuthenticationScheme);
            var task = context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), new AuthenticationProperties
            {
                IsPersistent = true,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(_jwtOptions.Expires)
            });
            task.Wait();

            var jwtSecurityToken = new JwtSecurityToken(
              issuer: _jwtOptions.Issuer,
              audience: _jwtOptions.Audience,
              claims: claims,
              expires: DateTime.UtcNow.AddMinutes(_jwtOptions.Expires),
              signingCredentials: _jwtOptions.SigningCredentials
            );
            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            //context.Response.Cookies.Delete(COOKIE_ADMIN_TOKEN);
            //context.Response.Cookies.Append(COOKIE_ADMIN_TOKEN, token,new CookieOptions() { MaxAge  =   TimeSpan.FromMinutes(_jwtOptions.Expires) });
            //SaveToken(user_id, jwtSecurityToken.Id, token); // 把token 缓存 
            return token;
        }
        /// <summary>
        /// 获取Token
        /// </summary>
        /// <param name="_jwtOptions">The JWT options.</param>
        /// <param name="user_id">The user identifier.</param>
        /// <param name="organization">The organization.</param>
        /// <param name="realName">Name of the real.</param>
        /// <param name="is_sup">The is sup.</param>
        /// <returns></returns>
        public static string GetToken(HttpContext context, JwtSecurityTokenOptions _jwtOptions)
        {
           var claims = context.User.Claims;
           var jwtSecurityToken = new JwtSecurityToken(
              issuer: _jwtOptions.Issuer,
              audience: _jwtOptions.Audience,
              claims: claims,
              expires: DateTime.UtcNow.AddMinutes(_jwtOptions.Expires),
              signingCredentials: _jwtOptions.SigningCredentials
            );
            string token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            //SaveToken(user_id, jwtSecurityToken.Id, token); // 把token 缓存 
            return token;
        }
        public static void SignOut(HttpContext context) {

            var task = context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            task.Wait();
            //context.Response.Cookies.Delete(COOKIE_ADMIN_TOKEN);
        }
        //private static void SaveToken(string user_id,string id, string token) {
        //    string key = "Token:"+user_id + "-" + id;
        //    var cacheOpt = new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) };
        //    CacheHelper.RemoveByStartsWith(user_id + "-");
        //    CacheHelper.SetString(key, token, cacheOpt);
        //}
    }
}
